<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="UTF-8">
        <style type="text/css">
      #map, html, body {
        padding: 0;
        margin: 0;
        height: 100%;
      }

      #panel {
        width: 200px;
        font-family: Arial, sans-serif;
        font-size: 13px;
        float: right;
        margin: 10px;
      }

      #color-palette {
        clear: both;
      }

      .color-button {
        width: 14px;
        height: 14px;
        font-size: 0;
        margin: 2px;
        float: left;
        cursor: pointer;
      }

      #delete-button {
        margin-top: 5px;
      }
  	  
    </style>
    <title>Open Play Place Tools</title>
    <script type="text/javascript"
      src="http://maps.google.com/maps/api/js?&sensor=false&libraries=drawing"></script>
    <script type="text/javascript">
      var drawingManager;
      var selectedShape;
      var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
      var selectedColor;
      var colorButtons = {};
      var map;
      var i = 0;
      var geocoder = new google.maps.Geocoder();
  	  var centerChangedLast;
      var reverseGeocodedLast;
      var currentReverseGeocodeResponse;

      function clearSelection() {
        if (selectedShape) {
          selectedShape.setEditable(false);
          selectedShape = null;
        }
      }

      function setSelection(shape) {
        clearSelection();
        selectedShape = shape;
        shape.setEditable(true);
        selectColor(shape.get('fillColor') || shape.get('strokeColor'));
      }

      function deleteSelectedShape() {
        if (selectedShape) {
          selectedShape.setMap(null);
        }
      }

      function selectColor(color) {
        selectedColor = color;
        for (var i = 0; i < colors.length; ++i) {
          var currColor = colors[i];
          colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
        }

        // Retrieves the current options from the drawing manager and replaces the
        // stroke or fill color as appropriate.
        var polylineOptions = drawingManager.get('polylineOptions');
        polylineOptions.strokeColor = color;
        drawingManager.set('polylineOptions', polylineOptions);

        var rectangleOptions = drawingManager.get('rectangleOptions');
        rectangleOptions.fillColor = color;
        drawingManager.set('rectangleOptions', rectangleOptions);

        var circleOptions = drawingManager.get('circleOptions');
        circleOptions.fillColor = color;
        drawingManager.set('circleOptions', circleOptions);

        var polygonOptions = drawingManager.get('polygonOptions');
        polygonOptions.fillColor = color;
        drawingManager.set('polygonOptions', polygonOptions);
      }

      function setSelectedShapeColor(color) {
        if (selectedShape) {
          if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
            selectedShape.set('strokeColor', color);
          } else {
            selectedShape.set('fillColor', color);
          }
        }
      }

      function makeColorButton(color) {
        var button = document.createElement('span');
        button.className = 'color-button';
        button.style.backgroundColor = color;
        google.maps.event.addDomListener(button, 'click', function() {
          selectColor(color);
          setSelectedShapeColor(color);
        });

        return button;
      }

       function buildColorPalette() {
         var colorPalette = document.getElementById('color-palette');
         for (var i = 0; i < colors.length; ++i) {
           var currColor = colors[i];
           var colorButton = makeColorButton(currColor);
           colorPalette.appendChild(colorButton);
           colorButtons[currColor] = colorButton;
         }
         selectColor(colors[0]);
       }
       
       function geocodePosition(pos) {
  			geocoder.geocode({
    		latLng: pos
  	   }, function(responses) {
    	   if (responses && responses.length > 0) {
      		updateMarkerAddress(responses[0].formatted_address);
    	   } else {
      		updateMarkerAddress('Cannot determine address at this location.');
           }
  		   });
	   }
		

	   
	   function updateMarkerStatus(str) {
  		document.getElementById('markerStatus').innerHTML = str;
	   }
	   
	   function updateMarkerPosition(latLng) {
  		document.getElementById('info').innerHTML = [
    		latLng.lat(),
    		latLng.lng()
  		].join(', ');
	   }

	   function updateMarkerAddress(str) {
  		document.getElementById('address').innerHTML = str;
       }

      function initialize() { 
      	var latlng = new google.maps.LatLng(32.5468,-23.2031);
      	var myOptions = {
          zoom: 3,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          disableDefaultUI: false,
          zoomControl: true
        };
        var marker = new google.maps.Marker({
    		position: latlng,
    		title: 'Point A',
    		map: map,
    		draggable: true
  		});
        
          // Update current position info.
  		//updateMarkerPosition(latlng);
  		//geocodePosition(latlng);
  
  		// Add dragging event listeners.
  		google.maps.event.addListener(marker, 'dragstart', function() {
    		updateMarkerAddress('Dragging...');
  		});
  
  		google.maps.event.addListener(marker, 'drag', function() {
    		updateMarkerStatus('Dragging...');
    		updateMarkerPosition(marker.getPosition());
  		});
  
  		google.maps.event.addListener(marker, 'dragend', function() {
    		updateMarkerStatus('Drag ended');
    		updateMarkerPosition(marker.getPosition());
    		attachMessage(marker, latlng);
    		geocodePosition(marker.getPosition());
  		}); 
  		  
        map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);

        var polyOptions = {
          strokeWeight: 0,
          fillOpacity: 0.45,
          editable: true
        };
        
        // Creates a drawing manager attached to the map that allows the user to draw
        // markers, lines, and shapes.
        drawingManager = new google.maps.drawing.DrawingManager({
        // Change drawing mode to be translate by default instead of drawing polygon
          //drawingMode: google.maps.drawing.OverlayType.POLYGON,
          markerOptions: {
            draggable: true
          },
          polylineOptions: {
            editable: true
          },
          rectangleOptions: polyOptions,
          circleOptions: polyOptions,
          polygonOptions: polyOptions,
          map: map
        });
        google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
          if (e.type != google.maps.drawing.OverlayType.MARKER) {
            // Switch back to non-drawing mode after drawing a shape.
            drawingManager.setDrawingMode(null);

            // Add an event listener that selects the newly-drawn shape when the user
            // mouses down on it.
            var newShape = e.overlay;
            newShape.type = e.type;
            google.maps.event.addListener(newShape, 'click', function() {
              setSelection(newShape);
            });
            setSelection(newShape);
          } 
        });
  		

        // Clear the current selection when the drawing mode is changed, or when the
        // map is clicked.
        google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
        google.maps.event.addListener(map, 'click', clearSelection);
        google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
        
        buildColorPalette();
        
        reverseGeocodedLast = new Date();
        centerChangedLast = new Date();
        
        setInterval(function() {
      		if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
        	  if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
          		reverseGeocode();
      		}
    	}, 1000);
    	
        //google.maps.event.addListener(map, 'zoom_changed', function() {
      	//	document.getElementById("zoom_level").innerHTML = map.getZoom();
    	//});

  
    	
    	//google.maps.event.addListener(map, 'center_changed', centerChanged);
    	
    	google.maps.event.addDomListener('marker','dblclick', function() {
       		infowindow.open(map,marker);;
    	});


      }


function attachMessage(marker, latlng) {
  var message = "This message located " + latlng.toString();
  var infowindow = new google.maps.InfoWindow(
      { content: message,
        size: new google.maps.Size(50,50)
      });
  //google.maps.event.addListener(marker, 'click', function() {
  //  infowindow.open(map,marker);
  //});
}
    
  function getCenterLatLngText() {
    return '(' + map.getCenter().lat() +', '+ map.getCenter().lng() +')';
  }
  	  function centerChanged() {
    	centerChangedLast = new Date();
    	var latlng = getCenterLatLngText();
    	document.getElementById('latlng').innerHTML = latlng;
    	document.getElementById('formatedAddress').innerHTML = '';
    	currentReverseGeocodeResponse = null;
  	  } 
  	  
  function reverseGeocodeResult(results, status) {
    currentReverseGeocodeResponse = results;
    if(status == 'OK') {
      if(results.length == 0) {
        document.getElementById('formatedAddress').innerHTML = 'None';
      } else {
        document.getElementById('formatedAddress').innerHTML = results[0].formatted_address;
      }
    } else {
      document.getElementById('formatedAddress').innerHTML = 'Error';
    }
  }
  function geocode() {
    var address = document.getElementById("address").value;
    geocoder.geocode({
      'address': address,
      'partialmatch': true}, geocodeResult);
  }	 
  function geocodeResult(results, status) {
    if (status == 'OK' && results.length > 0) {
      map.fitBounds(results[0].geometry.viewport);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  } 
 
  	  
      google.maps.event.addDomListener(window, 'load', initialize);
      
    </script>
  </head>
  <body>
  Find Place: <input type="text" id="address"/>
  <input type="button" value="Go" onclick="geocode()">
    <div id="panel">
      <div id="color-palette"></div>
      <div>
        <button id="delete-button">Delete Selected Shape</button>
      </div>
    </div>
    <div id="map">
    	<div id="map_canvas" style="width:100%; height:400px"></div>
    </div>
      <div id="infoPanel">
    	<b>Marker status:</b>
    	<div id="markerStatus"><i>Click and drag the marker.</i></div>
    	<b>Current position:</b>
    	<div id="info"></div>
    	<b>Closest matching address:</b>
    	<div id="address"></div>
  	  </div>
  </body>
</html>
